import React, { Fragment, useCallback, useEffect } from "react";
import { NoticeBar, Swiper, Toast } from "antd-mobile";
import NavBar from "@/components/NavBar/NavBar";
import SearchBar from "@/components/SearchBar/SearchBar";
import NavGrid from "@/views/Home/components/NavGrid/NavGrid";
import Like from "@/views/Home/components/Like/Like";
import { fetchHomeDataThunk } from "@/store/modules/homeStore";
import { useEnhanceDispatch, useEnhanceSelector } from "@/hooks";
import type { PageData } from "@/type/HomeType";
import { useNavigate } from "react-router-dom";
import "./Home.scss";

const Home: React.FunctionComponent = () => {
   const navigate = useNavigate();
   const enhanceDispatch = useEnhanceDispatch();
   const pageData: PageData = useEnhanceSelector(state => state.homeStore.homeData.pageData);
   /**
    * @description 获取首页所有数据的回调函数
    * */
   const fetchHomeData = useCallback(async () => {
      try {
         await enhanceDispatch(fetchHomeDataThunk("0")).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   }, []);

   /**
    * @description 跳转搜索页面的回调函数
    * */
   const goToSearch = () => {
      navigate("/search");
   };


   useEffect(() => {
      fetchHomeData();
   }, []);

   const renderHomePage = () => {
      if (pageData) {
         return (
            <Fragment>
               {/*导航栏组件*/}
               <NavBar children="智慧商城"></NavBar>
               {/* 搜索组件*/}
               <SearchBar placeholder={pageData.items[0].params.placeholder} onClick={goToSearch}></SearchBar>
               {/* 轮播图组件 */}
               <Swiper loop autoplay>
                  {pageData.items[1].data.map((item, index) => <Swiper.Item key={index} onClick={() => navigate(`/good-detail?goodsId=${item.link.form[0].value}`)}><img src={item.imgUrl} alt="" /></Swiper.Item>)}
               </Swiper>
               {/* 通告栏组件 */}
               <NoticeBar content={pageData.items[2].params.text + pageData.items[2].params.text} />
               {/*分类九宫格组件*/}
               <NavGrid navList={pageData.items[3].data}></NavGrid>
               {/*  宣传图片 */}
               <img src={pageData.items[4].data[0].imgUrl} className="activity" />
               {/* 猜你喜欢*/}
               <Like title="猜你喜欢" goodList={pageData.items[6].data}></Like>
               {/* 人气推荐*/}
               <Like title="人气推荐" goodList={pageData.items[6].data}></Like>
            </Fragment>
         );
      }
   };
   return <div className="home-container">{renderHomePage()}</div>

};

export default Home;
